package org.jboss.as.quickstarts.login.stripes;

import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.jboss.as.quickstarts.login.Credentials;
import org.jboss.as.quickstarts.login.LoggedIn;
import org.jboss.as.quickstarts.login.User;
import org.jboss.as.quickstarts.login.UserManager;

import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Gregory Rushton, gregory.rushton@gmail.com
 *         Date: 9/7/11
 *         Time: 8:55 AM
 */
@UrlBinding("/Stripes/Login.action")
public class LoginActionBean extends BaseActionBean {

    @Inject
    private UserManager userManager;

    @Inject
    private transient Logger logger;

    @ValidateNestedProperties({
            @Validate(field = "username", required = true, on = {"login"}),
            @Validate(field = "password", required = true, on = {"login"})
    })
    private Credentials credentials;

    public Credentials getCredentials() {
        return credentials;
    }

    @SuppressWarnings({"unused"})
    public void setCredentials(Credentials credentials) {
        this.credentials = credentials;
    }

    @Produces
    @LoggedIn
    public User getCurrentUser() {
        return getContext().getCurrentUser();
    }

    private void setCurrentUser(User currentUser) {
        getContext().setCurrentUser(currentUser);
    }

    @DefaultHandler
    @HandlesEvent("view")
    public Resolution view() {
        return new ForwardResolution(STRIPES_LOGIN_JSP);
    }

    @HandlesEvent("login")
    public Resolution login() {
        User user = null;
        try {
            user = userManager.findUser(getCredentials().getUsername(), getCredentials().getPassword());
        } catch (Exception e) {
            logger.log(Level.ALL, "Exception finding credentials: " + getCredentials().toString());
            getContext().getValidationErrors().addGlobalError(new SimpleError("Sorry, exception occurred finding the user name and password provided. "));
        }
        if (user != null) {
            setCurrentUser(user);
            getContext().getMessages().add(new SimpleMessage("Welcome, " + getCurrentUser().getName()));
            return new ForwardResolution(UsersActionBean.class);
        } else {
            getContext().getValidationErrors().addGlobalError(new SimpleError("Sorry, cannot find the user name and password provided. "));
            return view();
        }
    }

    @SuppressWarnings({"NullableProblems"})
    @HandlesEvent("logout")
    public Resolution logout() {
        setCurrentUser(null);
        return new ForwardResolution(INDEX_JSP);
    }

    public boolean isLoggedIn() {
        return getCurrentUser() != null;
    }

}
